import IndexService from '@/services/index.service';
import { NextFunction, Request, Response } from 'express';
import { decodeMsg, getMsg } from '@utils/qy-sdk';
import { AuthProps, BodyProps, CorpProps, MsgProps } from '@interfaces/index.interface';
import moment from 'moment';
import MsgService from '@services/msg.service';
import { miniMsgContentProps, miniMsgProps } from '@interfaces/msg.interface';
import UserService from '@services/users.service';

class IndexController {
  public indexService = new IndexService();
  public msgService = new MsgService();
  public userService = new UserService();

  public testHandle = async (req: Request, res: Response, next: NextFunction) => {
    // 发送文本消息
    // const result = await this.msgService.sendTextMsg('ww66c1ab0a3c5963a3', 'JinZhi', 'text Info');
    // 发送小程序消息
    // const body: miniMsgContentProps = {
    //   page: 'pages/loading?type=test',
    //   title: '测试小程序消息',
    //   description: '小程序消息副标题',
    //   content_item: [
    //     {
    //       key: '书名',
    //       value: '围城',
    //     },
    //     {
    //       key: '借书日期',
    //       value: '2021-06-23',
    //     },
    //   ],
    // };
    // const result = await this.msgService.sendMiniMsg('ww66c1ab0a3c5963a3', 'JinZhi', body);
    // res.send(result);

    // const result = await this.indexService.convertToOpenId('ww66c1ab0a3c5963a3', 'JinZhi');
    // res.send(result.data);
    res.status(200).send('success');
  };

  public getWecomMsg = async (req: Request, res: Response, next: NextFunction) => {
    const query: any = req.query;
    const result: MsgProps = await decodeMsg(query.timestamp, query.nonce, query.echostr, query.msg_signature);
    res.status(200).send(result?.message);
  };

  public getWecomCommand = async (req: Request, res: Response, next: NextFunction) => {
    res.status(200).send('success');
    const query: any = req.query;
    const body: BodyProps = req.body;
    const msgRes = await getMsg<AuthProps>(query.timestamp, query.nonce, body.xml.Encrypt, query.msg_signature);
    await this.indexService.saveWeworkMsg({
      msg: JSON.stringify(msgRes),
    });
    const type = msgRes.InfoType && msgRes.InfoType[0];
    if (type === 'suite_ticket') {
      // 企业微信会每 10 分钟推送一次suite_ticket,当类型是 suite_ticket 类型时，需要把 suite_ticket 保存起来，有效期为 30 分钟
      // 相关文档：https://work.weixin.qq.com/api/doc/90001/90143/90600
      await this.indexService.addSuiteTicket({
        ticket: msgRes.SuiteTicket[0],
      });
      await this.indexService.checkAndUpdateAccessToken();
    } else if (type === 'create_auth') {
      const authCode = msgRes.AuthCode[0];
      const p = await this.indexService.getPermanentCode(authCode);
      const corp: CorpProps = {
        accessToken: p.access_token,
        expiresIn: p.expires_in,
        accessTokenExpiresAt: moment().add(p.expires_in, 'seconds').toDate(),
        permanentCode: p.permanent_code,
        corpId: p.auth_corp_info.corpid,
        corpName: p.auth_corp_info.corp_name,
        corpType: p.auth_corp_info.corp_type,
        corpRoundLogoUrl: p.auth_corp_info.corp_round_logo_url,
        corpSquareLogoUrl: p.auth_corp_info.corp_square_logo_url,
        corpUserMax: p.auth_corp_info.corp_user_max,
        corpAgentMax: p.auth_corp_info.corp_agent_max,
        corpFullName: p.auth_corp_info.corp_full_name,
        subjectType: p.auth_corp_info.subject_type,
        qrcode: p.auth_corp_info.corp_wxqrcode,
        scale: p.auth_corp_info.corp_scale,
        industry: p.auth_corp_info.corp_industry,
        subIndustry: p.auth_corp_info.corp_sub_industry,
        location: p.auth_corp_info.location,
        userid: p.auth_user_info.userid,
        name: p.auth_user_info.name,
        avatar: p.auth_user_info.avatar,
        openUserId: p.auth_user_info.open_userid,
        agentId: p.auth_info.agent[0].agentid,
        agentName: p.auth_info.agent[0].name,
        agentLogo: p.auth_info.agent[0].square_logo_url,
        msg: JSON.stringify(p),
      };
      await this.indexService.saveCorpInfo(corp);
      await this.indexService.getDeptListFromWework(corp.corpId);
      await this.indexService.getDeptListFromDb(corp.corpId);
      await this.indexService.createlibrary(corp.corpId);
    } else if (type === 'cancel_auth') {
      // 取消授权，即删除小程序
      await this.indexService.disabledCorp(msgRes.AuthCorpId[0]);
    } else if (type === 'change_contact') {
      // 修改通讯录信息
      const changeType = msgRes.ChangeType && msgRes.ChangeType[0];
      if (changeType === 'update_user') {
        const corpId = msgRes.AuthCorpId && msgRes.AuthCorpId[0];
        const oldUserId = msgRes.UserID && msgRes.UserID[0];
        const newUserId = msgRes.NewUserID && msgRes.NewUserID[0];
        await this.userService.updateUserId({
          userId: oldUserId,
          newUserId,
          corpId,
        });
      }
      // await this.indexService.disabledCorp(msgRes.AuthCorpId[0]);
    }
  };
}

export default IndexController;
